﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Web;
using System.Text;

//自定义命名空间
using DreamCube.Foundation.Basic.Objects.Log;
using DreamCube.Foundation.Basic.Enums;
using DreamCube.Foundation.Basic.Extensions.System;
using DreamCube.Framework.DataAccess.Basic;
using DreamCube.Framework.DataAccess.Sqlserver;

using DreamCube.DC_52Icon.BLL;

namespace DreamCube.DC_52Icon
{
    public partial class search : System.Web.UI.Page
    {
        #region "私有字段"

        /// <summary>
        /// 图片尺寸的queryString值范围，不在此范围内的数据表示异常
        /// </summary>
        private static List<String> imageSizeValuesRange = new List<String> { "allsize", "size12", "size16", "size24", "size32", "size48", "size64", "size128", "size256" };

        /// <summary>
        /// 图片类型（格式）的queryString值范围，不在此范围内的数据表示异常
        /// </summary>
        private static List<String> iamgeTypeValuesRange = new List<String> { "all", "icon", "png" };

        /// <summary>
        /// 图标数据表所有的记录图标的列
        /// </summary>
        private static List<String> iconTableColumns =
            new List<String> { "size12", "icon12", "size16", "icon16", "size24", 
                               "icon24", "size32", "icon32", "size48", "icon48", 
                               "size64", "icon64", "size128" ,"icon128","size256","icon256"};

        /// <summary>
        /// 图片服务器的基地址
        /// </summary>
        public static String imageServiceUrl = ConfigurationManager.AppSettings["imageServerBasicUrl"];

        /// <summary>                                                          
        /// 图标的HTML模板                                                  
        /// {0}--表示图片的code(图片记录的主键值)                                              
        /// {1}--表示图片的背景颜色  
        /// {2}--表示查询的关键字
        /// {3}--表示图片的keyword                                         
        /// {4}--表示图片的路径                                            
        /// {5}--表示图片大小的风格                                      
        /// {6}--表示loading gif图片                                       
        /// {7}--表示加载错误时的默认图片                                     
        /// </summary>                                                   
        private static String IconImageHtml = "<DIV id='icon_{0}' class='icon {1}'>" + 
                                                  "<A id='iconurl_{0}' class='iconlink' title='{2}' href='details.aspx?id={0}&w={2}'>" +
                                                      "<IMG {5} IsNeedLoad='true' alt='{3}' targetSrc='{4}' src='{6}' loadingImage='{6}' errorImgSrc='{7}' divID='icon_{0}' id='imageID_{0}' />" +
                                                  "</A>" + 
                                               "</DIV>";

        #endregion

        #region "受保护方法"

        protected void Page_Load(object sender, EventArgs e)
        {
            //图片尺寸
            String imageSize = Request.QueryString["size"];
            imageSize = String.IsNullOrEmpty(imageSize) ? imageSizeValuesRange[0] : imageSize.ToLower();
            if (!imageSizeValuesRange.Contains(imageSize)) return;

            //图片类型（格式）
            String imageType = Request.QueryString["it"];
            imageType = String.IsNullOrEmpty(imageType) ? iamgeTypeValuesRange[0] : imageType.ToLower();
            if (!iamgeTypeValuesRange.Contains(imageType)) return;

            String page = Request.QueryString["p"]; //当前的页码
            String pageSize = Request.QueryString["ps"];//每页显示图片个数

            //查询的关键字
            String queryKeyWord = HttpUtility.UrlDecode(Request.QueryString["w"]);
            tKey.Text = queryKeyWord;
            try
            {
                if (!Page.IsPostBack)
                    LoadImages(page.TryToInt32(OperType.StillReturnWithoutLogWhenFail, 1),
                               pageSize.TryToInt32(OperType.StillReturnWithoutLogWhenFail, 14),
                               imageSize,
                               imageType,
                               queryKeyWord);
            }
            catch (Exception ex)
            { LoggerManager.Logger.MakeLogAsync(ex); }
        }

        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="iamgeSize"></param>
        /// <param name="imageType"></param>
        /// <param name="querykeyWord"></param>
        private void LoadImages(Int32 pageNumber, Int32 pageSize, String iamgeSize, String imageType, String querykeyWord)
        {
            Database db = DbManager.GetDBByName("icondb");
            DbCommand command = db.GetStoredProcCommand(GetProcName(iamgeSize, imageType));
            db.DiscoverParameters(command);
            db.SetParameterValue(command, "@pageSize", pageSize);
            db.SetParameterValue(command, "@pageNumber", pageNumber);
            db.SetParameterValue(command, "@keyword", querykeyWord);
            db.SetParameterValue(command, "@totalRecordSum", pageSize);

            DataTable table = db.ExecuteDataTable(command);
            if (table == null || table.Rows.Count <= 0) return;

            Int32 totalRecordCount =
                command.Parameters["@totalRecordSum"].Value.TryToInt32(OperType.StillReturnWithoutLogWhenFail, 1);

            //创建图片
            CreateImage(table, querykeyWord);
            //把总数显示到页面上
            tCount.Text = totalRecordCount.ToString();

            //创建页码
            CreatePageNumber(totalRecordCount, pageSize, pageNumber);
        }

        /// <summary>
        /// 创建图片的HTML内容并输出到页面
        /// </summary>
        /// <param name="table">查询到的图片数据</param>
        /// <param name="querykeyWord"></param>
        protected void CreateImage(DataTable table, String querykeyWord)
        {
            StringBuilder icons = new StringBuilder();
            for (Int32 i = 0; i < table.Rows.Count; i++)
            {
                String code = table.Rows[i]["code"].ToStringEx();
                String keyWord = table.Rows[i]["keyword"].ToStringEx();
                String zhKeyWord = table.Rows[i]["zhkeyword"].ToStringEx();
                String imageUnicodeID = "-1";
                //保存图片的大小的css风格，当图片大小为256时，显示太大了，要固定成显示150 * 150
                String imageSizeStyle = "";
                //获取一个可以显示的图片
                for (Int32 j = table.Columns.Count - 1; j > 0; j--)
                {
                    String columnName = table.Columns[j].ColumnName.ToLower();
                    if (iconTableColumns.Contains(columnName))
                    {
                        String tempValue = table.Rows[i][j].ToStringEx();
                        if (tempValue == "-1") continue;
                        Int64 tempImageUnicode;
                        if (Int64.TryParse(tempValue, out  tempImageUnicode))
                        {
                            if (columnName.IndexOf("256") >= 0) imageSizeStyle = "style='height:150px;width:150px'";
                            imageUnicodeID = tempValue;
                            break;
                        }
                    }
                }
                /// 图标的HTML模板                                                  
                /// {0}--表示图片的code                                              
                /// {1}--表示图片的背景颜色  
                /// {2}--表示查询的关键字
                /// {3}--表示图片的keyword                                         
                /// {4}--表示图片的路径                                            
                /// {5}--表示图片大小的风格                                      
                /// {6}--表示loading gif图片                                       
                /// {7}--表示加载错误时的默认图片   
                //获取一张预览图片
                icons.AppendFormat(IconImageHtml,
                                    code,
                                    Request.QueryString["bg"],
                                    querykeyWord,
                                    keyWord + zhKeyWord,
                                    imageServiceUrl + "?id=" + imageUnicodeID,
                                    imageSizeStyle,
                                    Properties.Resources.loadingImageSrc,
                                    Properties.Resources.loadingErrorImage);
            }
            this.lt_icons.Text = icons.ToString();
        }

        /// <summary>
        /// 创建页码的HTML并输出到页面
        /// </summary>
        /// <param name="totalRecordCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPage"></param>
        protected void CreatePageNumber(Int32 totalRecordCount, Int32 pageSize, Int32 currentPage)
        {
            StringBuilder navigationHtml = new StringBuilder();
            Int32 pageCount = (Int32)Math.Floor((Double)((Double)totalRecordCount) / (Double)pageSize);
            if (pageCount == 1 || pageCount == 0) return;
            //显示10个分页数字
            Int32 numberShow = 10;
            Int32 middleNum = numberShow / 2;
            Int32 startNumber = currentPage + middleNum;
            if (startNumber < numberShow) startNumber = numberShow;
            if (startNumber > pageCount) startNumber = pageCount;
            //创建末页下一页按钮
            if (currentPage != pageCount)
                navigationHtml.Append("<A href='#' onclick='Update(" + pageCount + ")'>末页(共" + pageCount + "页)</A><A href='#' onclick='Update(" + (currentPage + 1) + ")'>下一页</A>");
            else
                navigationHtml.Append("<A>末页(共" + pageCount + "页)</A><A>下一页</A>");

            //创建分页按钮数字（10个数字，当前页面为中间）
            for (Int32 i = startNumber, j = Math.Max(0, startNumber - numberShow); i > j; i--)
            {
                //显示上一页
                if (currentPage == i)
                    navigationHtml.Append("<SPAN class='selected'><B>" + i + "</B></SPAN>");
                else
                    navigationHtml.Append("<A href='#' onclick='Update(" + i + ")'>" + i + "</A>");
            }

            //创建上一页首页按钮
            if (currentPage != 1)
                navigationHtml.Append("<A href='#' onclick='Update(" + (currentPage - 1) + ")'>上一页</A><A href='#' onclick='Update(1)'>首页</A>");
            else
                navigationHtml.Append("<A>上一页</A><A>首页</A>");

            this.nav.Text = navigationHtml.ToString();
        }

        #endregion

        #region "静态辅助方法"

        /// <summary>
        /// 根据图片类型和型号，获取存储过程名
        /// </summary>
        /// <param name="imageSize"></param>
        /// <param name="imageType"></param>
        /// <returns></returns>
        private static String GetProcName(String imageSize, String imageType)
        {
            String procNameTemplate = "Get{0}Images{1}";
            return String.Format(procNameTemplate, imageType, imageSize);
        }

        #endregion
    }
}